package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
//        缓存穿透处理
//        Shop shop = queryWithPassThrough(id);
//        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);


//        互斥锁解决缓存击穿
//        Shop shop = queryWithMutex(id);

//        逻辑过期解决缓存击穿
//        Shop shop = queryWithLogicExpire(id);
        Shop shop = cacheClient.queryWithLogicExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("获取店铺信息失败！");
        }
        return Result.ok(shop);
    }

    /**
     * 模拟逻辑日期
     *
     * @param id
     * @return
     */
    public Shop queryWithLogicExpire(Long id) {
        //从redis查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
//      如果未命中说明缓存被使用，直接返回null
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
//        命中，就先把Json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
//        判断expire属性是否过期，如果未过期就直接返回
        if (expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }
//        如果已过期，就重建缓存
//        要先获取互斥锁，判断是否获取锁成功
        String lockKey = LOCK_SHOP_KEY + id;
        Boolean shopLock = tryLock(lockKey);
//        如果成功，就开启新线程实现缓存重建
        if (shopLock) {
            CACHE_REBUILDER_EXECUTOR.submit(() -> {
                try {
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
//                释放锁
                    unLock(lockKey);
                }
            });
        }
//        如果没拿到锁，就返回过期的店铺信息
        return shop;
    }

    /*创建一个线程池*/
    private static final ExecutorService CACHE_REBUILDER_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 在商品信息中添加逻辑日期属性
     *
     * @param id
     * @param expireSeconds
     */
    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
//        缓存重建前设置个延迟模拟高并发状态
        Thread.sleep(200);
        RedisData redisData = new RedisData();
//        查寻商品
        Shop shop = getById(id);
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//        写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 防止缓存穿透➕互斥锁
     *
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id) {
        //从redis查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
//    判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
//         判断命中的是否为空值
        if (shopJson != null) {
            return null;
        }
//        以下开始缓存重建（引入互斥锁）
//        获取互斥锁
        String lockKey = "lock:shop:" + id;
        Shop shop = null;
        try {
            Boolean isLock = tryLock(lockKey);
//        判断是否获取成功 失败就休眠并重试（自旋）
            if (!isLock) {/*拿锁失败，休眠递归重试*/
                Thread.sleep(50);
                return queryWithMutex(id);
            }
//    redis中不存在，根据id查询数据库
            shop = getById(id);
//            模拟重建的延时
            Thread.sleep(200);
//    数据库不存在，返回错误
            if (shop == null) {
                //            先设置为空字符串
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
//        成功就根据id查询并写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //        释放互斥锁
            unLock(lockKey);
        }
//        返回
        return shop;
    }

    /**
     * 防止缓存穿透
     *
     * @param id
     * @return
     */
   /* public Shop queryWithPassThrough(Long id) {
        //从redis查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
//    判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
//        判断命中的是否为空值
        if (shopJson != null) {
            return null;
        }
//    不存在，根据id查询数据库
        Shop shop = getById(id);
//    数据库不存在，返回错误
        if (shop == null) {
//            先设置为空字符串
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
//    数据库存在，写入redis，返回结果
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }*/

    /**
     * 加锁
     *
     * @param key
     */
    public Boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 20, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     *
     * @param key the key
     */
    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional/*缓存和数据库操作要具有原子性*/ public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("商铺不能为空！");
        }
//        更新数据库，删除缓存
        updateById(shop);
//        删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

}
